import fs from 'fs/promises'
import path from 'path'
import { Result } from '~~/lib/helper/result'
import prisma from '~~/lib/prisma'

export default defineEventHandler(async (event) => {
  const body = await readMultipartFormData(event)
  const userId = getLoginId(event)
  try {
    if (body) {
      const fileType = body[0].type
      if (
        fileType == 'image/jpeg' ||
        fileType == 'image/png' ||
        fileType == 'image/jpg'
      ) {
        const serverPublic = path.join(process.cwd(), 'public')
        const fileName = body[0].filename!
        const absPath = ['upload', 'image', fileName].join('/')
        const filePath = path.join(serverPublic, absPath)
        const buffer = body[0].data!
        await fs.writeFile(filePath, buffer)
        await prisma.user.update({
          where: { id: userId },
          data: { avatar: absPath },
        })
        return Result.Ok(absPath, 200, '上传头像成功！')
      } else {
        return Result.Error('头像格式错误！')
      }
    } else {
      return Result.Error('请上传头像！')
    }
  } catch (error: any) {
    console.log('error', error)
    return Result.Error('上传头像失败！' + error.messsage)
  }
})
